/*
 * @Descripttion: 
 * @version: 
 * @Author: yuanliutech
 * @Date: 2022-11-01 14:23:34
 * @LastEditors: yuanliutech@lwj
 * @LastEditTime: 2023-02-15 11:48:52
 */
const app = getApp()
import {
    showMsg
} from '../../../../utils/config.js'
import {
    validateEmoji,
    validateSpecial
} from '../../../../utils/validate.js'
let spacePopoverSel = require('../behaviors/space/space-popover-sel.js')
import {
    reqisolationPersonAdd,
    reqRegion,
    reqRegionLevel,
} from '../../../../request/api'
let util = require("../../../../utils/util.js");
let arr = []
for (let i = 2; i < 30; i++) {
    arr.push(i)
}
Page({
    behaviors: [spacePopoverSel], //空间弹窗选择混入
    data: {
        navHeight: app.globalData.navHeight + 'px', //头部距离
        bottomHeight: app.globalData.bottomHeight + 'px', //iphone底部距离
        form: {
            room: '',
            type: '',
            typeText: '',
            mode: '',
            modeText: '',
            // startTime: `${util.formatDate(Date.parse(new Date()))} 00:00:00`,
            startTime: `${util.formatTime(new Date())}`,
            // region: ['省', '市', "区"],
            region: '',
            days: ''
        },

        // 隔离因素开始
        showIsolationType: false,
        isolationTypeList: [{
            id: 1,
            text: '密接',
        }, {
            id: 2,
            text: '次密接',
        }, {
            id: 3,
            text: '确诊',
        }, ],
        // 隔离因素结束

        // 隔离方式开始
        showIsolationMode: false,
        isolationModeList: [{
            id: 1,
            text: '居家隔离',
        }, {
            id: 2,
            text: '酒店隔离',
        }, {
            id: 3,
            text: '定点医院隔离',
        }, {
            id: 4,
            text: '其他隔离'
        }, ],
        // 隔离方式结束

        // 来源地区选择开始
        showRegion: false,
        tabList: [{
            id: 0,
            name: '省',
        }, {
            id: 1,
            name: '市',
        }, {
            id: 2,
            name: '区',
        }, ],
        currentTab: 0,
        provinceList: [],
        provinceCode: '',
        provinceName: '',
        cityList: [],
        cityCode: '',
        cityName: '',
        areaList: [],
        areaCode: '',
        areaName: '',
        // 来源地区选择结束

        // 隔离开始时间开始  
        showStartTime: false,
        timePickerConfig: {
            isTabbar: false, //是否为tabbar页面
            endDate: false, // 是否需要结束时间，为true时显示开始时间和结束时间两个picker
            column: "minute", //可选的最小时间范围day、hour、minute、secend
            dateLimit: true,
            initStartTime: '',
            initEndTime: '',
            limitStartTime: "2015-01-01 00:00:00", //最小可选时间--必填
            limitEndTime: "2100-05-06 23:59:59" //最大可选时间--必填
        },
        // 隔离开始时间结束

        // 隔离天数开始
        showIsolationDay: false,
        isolationDayList: [1, ...arr, 30],
        // 隔离天数结束

        // 设备开始
        imeiList: [{
            id: 0,
            imei: '',
            type: ''
        }, ],
        // 设备结束

        // 隔离人开始
        peopleList: [{
            id: 0,
            name: '',
            gender: '',
            genderText: '',
            mobile: '',
            idCard: '',
        }, ],
        showIsolationGender: false,
        isolationGenderList: [{
                id: 0,
                text: "女"
            },
            {
                id: 1,
                text: '男'
            }
        ],
        genderId: '',
        // 隔离人结束

    },
    onLoad(e) {
        this.getItemInfo(e)
    },
    onShow() {
        this.getSpaceList()
        this.getRegion()
    },
    // 获取信息
    getItemInfo(e) {
        let info = JSON.parse(e.info)
        let {
            spaceId,
            spaceName
        } = info
        if (spaceId) {
            this.setData({
                spaceId,
                spaceName
            })
        }
    },
    /* --------------------------------隔离点开始-------------------------- */
    // 弹出隔离因素
    clickIsolationType() {
        this.setData({
            showIsolationType: true
        })
    },
    // 隐藏隔离因素
    isolationTypeClose() {
        this.setData({
            showIsolationType: false
        })
    },
    // 确定隔离因素
    isolationTypeConfirm(e) {
        const {
            value,
            index
        } = e.detail;
        this.setData({
            "form.type": value.id,
            "form.typeText": value.text,
            showIsolationType: false,
        })
    },
    // 弹出隔离方式
    clickIsolationMode() {
        this.setData({
            showIsolationMode: true
        })
    },
    // 隐藏隔离方式
    isolationModeClose() {
        this.setData({
            showIsolationMode: false
        })
    },
    // 确定隔离方式
    isolationModeConfirm(e) {
        const {
            value,
            index
        } = e.detail;
        this.setData({
            "form.mode": value.id,
            "form.modeText": value.text,
            showIsolationMode: false,
        })
    },
    // 来源地区开始
    swichTab(e) {
        let {
            id
        } = e.currentTarget.dataset
        this.setData({
            currentTab: id
        })
    },

    bindChangeTab(e) {
        let {
            current
        } = e.detail
        this.setData({
            currentTab: current
        })
    },
    // 弹出省市区
    showRegionClick() {
        this.setData({
            showRegion: true
        })
    },
    closeRegion() {
        this.setData({
            showRegion: false
        })
    },
    // 获取省级数据
    async getRegion() {
        const res = await reqRegion()
        if (res.code !== 20000) return showMsg(res.message)
        console.log(res);
        let {
            rows
        } = res.data
        this.setData({
            provinceList: rows
        })
    },
    // 点击省
    async provinceClick(e) {
        this.setData({
            cityList: [],
            areaList: [],
            cityCode: "",
            areaCode: "",
        })
        let {
            item
        } = e.currentTarget.dataset
        const res = await reqRegionLevel(item.regionCode)
        if (res.code !== 20000) return showMsg(res.message)
        let {
            rows
        } = res.data
        this.setData({
            provinceCode: item.regionCode,
            provinceName: item.regionName,
            cityList: rows,
            currentTab: 1,
        })
    },
    // 点击市
    async cityClick(e) {
        this.setData({
            areaList: [],
            areaCode: "",
        })
        let {
            item
        } = e.currentTarget.dataset
        const res = await reqRegionLevel(item.regionCode)
        if (res.code !== 20000) return showMsg(res.message)
        let {
            rows
        } = res.data
        this.setData({
            cityCode: item.regionCode,
            cityName: item.regionName,
            areaList: rows,
            currentTab: 2,
        })
    },
    // 点击区
    async areaClick(e) {
        this.setData({
            streetList: [],
            streetCode: "",
        })
        let {
            item
        } = e.currentTarget.dataset
        this.setData({
            areaCode: item.regionCode,
            areaName: item.regionName,
        })
    },
    // 确定
    confirmRegion() {
        let {
            areaCode,
            provinceName,
            cityName,
            areaName,
        } = this.data
        if (!areaCode) return showMsg("请选择到区")
        this.setData({
            'form.region': provinceName + cityName + areaName
        })
        this.closeRegion()
    },
    // 来源地区结束
    // 点击开始时间
    clickShowStartTime() {
        this.setData({
            showStartTime: true,
        });
    },
    // 隐藏开始时间
    startTimeClose() {
        this.setData({
            showStartTime: false,
        });
    },
    // 确定开始时间
    startTimeChange(e) {
        this.setData({
            'form.startTime': e.detail.startTime,
            showStartTime: false,
        });
    },

    // 输入天数获取
    dayChange(e) {
        let {
            value
        } = e.detail
        this.setData({
            "form.days": value
        })
        this.pickerDaysToggle(value)
    },
    // 隔离天数picker映射
    pickerDaysToggle(days) {
        let pickerDays = this.selectComponent('.picker-days')
        pickerDays.setIndexes([days - 1])
    },
    // 弹出天数弹窗
    clickIsolationDay() {
        this.setData({
            showIsolationDay: true
        })
    },
    // 隐藏天数弹窗
    isolationDayClose() {
        this.setData({
            showIsolationDay: false
        })
    },
    // 确定天数弹窗
    isolationDayConfirm(e) {
        const {
            value,
            index
        } = e.detail;
        this.setData({
            "form.days": value,
            showIsolationDay: false
        })
    },

    /* --------------------------------隔离点结束-------------------------- */


    /* --------------------------------设备开始-------------------------- */
    // 点击新增一条设备输入框
    clickAddDevice() {
        let {
            imeiList
        } = this.data
        let id = imeiList[imeiList.length - 1].id + 1
        imeiList.push({
            id,
            imei: '',
            type: ''
        })
        this.setData({
            imeiList
        })
    },
    // 获取设备imei
    imeiChange(e) {
        let {
            id
        } = e.target.dataset
        let {
            value
        } = e.detail
        let {
            imeiList
        } = this.data
        imeiList.forEach(item => {
            if (item.id === id) {
                item.imei = value
            }
        })
        this.setData({
            imeiList
        })
    },
         // js判断字符串是否为JSON格式
  isjson(str) {
    if (typeof str == 'string') {
        try {
            var obj = JSON.parse(str);
            if (typeof obj == 'object' && obj) {
                return true;
            } else {
                return false;
            }

        } catch (e) {
            console.log('error：' + str + '!!!' + e);
            return false;
        }
    }
    console.log('It is not a string!')
},
    /**
     * @name:  扫码imei
     * @msg: 掉接口时记得询问清楚截取方法
     * @return {*}
     */
    imeiScan(e) {
        let that = this
        let {
            id
        } = e.target.dataset
        let qrcode = ''
        wx.scanCode({
            success(res) {
                qrcode = res.result;
                if (!qrcode) return showMsg('扫描失败，请重新扫描')
                if (qrcode.length >= 3) {
                    if (that.isjson(qrcode)) {
                        const result = JSON.parse(qrcode);
                            // JSON字符格式
                            that.setData({
                                searchValue: result.ID, //威视达康摄像机取值，后续看需求更改 lc
                            })
                            that.imeiScanChange(id, result.ID)
                        } else {
                            // 非JSON格式
                            that.setData({
                                searchValue: qrcode,
                            })
                            that.imeiScanChange(id, qrcode)
                        }
                } else {
                    showMsg('扫描失败，请重新扫描')
                    return
                }
            }
        })
    },
    // 扫码后赋值imei
    imeiScanChange(id, code) {
        let {
            imeiList
        } = this.data
        imeiList.forEach(item => {
            if (item.id === id) {
                item.imei = code
            }
        })
        this.setData({
            imeiList
        })
    },
    // 清除imei
    imeiClear(e) {
        let {
            id
        } = e.target.dataset
        let {
            imeiList
        } = this.data
        imeiList.forEach(item => {
            if (item.id === id) {
                item.imei = ''
            }
        })
        this.setData({
            imeiList
        })
    },

    /* --------------------------------设备结束-------------------------- */


    /* --------------------------------隔离人开始-------------------------- */
    // 点击新增一条隔离人
    clickAddPeople() {
        let {
            peopleList
        } = this.data
        if (peopleList.length >= 10) return showMsg("一次最多新增10个隔离人")
        let id = peopleList[peopleList.length - 1].id + 1
        peopleList.push({
            id,
            name: '',
            gender: '',
            mobile: ''
        })
        this.setData({
            peopleList
        })
    },
    // 获取隔离人姓名
    isolationNameChange(e) {
        let {
            id
        } = e.target.dataset
        let value = validateEmoji(e.detail.value.replace(/\s+/g, ''))
        let {
            peopleList
        } = this.data
        peopleList.forEach(item => {
            if (item.id === id) {
                item.name = value
            }
        })
        this.setData({
            peopleList
        })
    },
    // 清除隔离人姓名
    clearName(e) {
        let {
            id
        } = e.target.dataset
        let {
            peopleList
        } = this.data
        peopleList.forEach(item => {
            if (item.id === id) {
                item.name = ''
            }
        })
        this.setData({
            peopleList
        })
    },
    /**
     * @name: 获取性别
     * @msg: 1、弹出弹窗   2、隐藏弹窗  3、确定值
     * @return {*}
     */
    // 弹出弹窗
    clickIsolationGender(e) {
        let {
            id
        } = e.currentTarget.dataset
        this.setData({
            showIsolationGender: true,
            genderId: id
        })
    },
    // 隐藏弹窗
    isolationGenderClose() {
        this.setData({
            showIsolationGender: false
        })
    },
    // 确定值
    isolationGenderConfirm(e) {
        const {
            value,
            index
        } = e.detail;
        let {
            peopleList,
            genderId
        } = this.data
        peopleList.forEach(item => {
            if (item.id === genderId) {
                item.gender = value.id
                item.genderText = value.text
            }
        })
        this.setData({
            showIsolationGender: false,
            peopleList
        })
    },

    // 获取隔离人电话
    isolationMobileChange(e) {
        let {
            id
        } = e.target.dataset
        let {
            value
        } = e.detail
        let {
            peopleList
        } = this.data
        peopleList.forEach(item => {
            if (item.id === id) {
                item.mobile = value
            }
        })
        this.setData({
            peopleList
        })
    },
    // 清除隔离人电话
    clearMobile(e) {
        let {
            id
        } = e.target.dataset
        let {
            peopleList
        } = this.data
        peopleList.forEach(item => {
            if (item.id === id) {
                item.mobile = ''
            }
        })
        this.setData({
            peopleList
        })
    },


    // 获取证件号
    isolationIdCardChange(e) {
        let {
            id
        } = e.target.dataset
        let {
            value
        } = e.detail
        let {
            peopleList
        } = this.data
        peopleList.forEach(item => {
            if (item.id === id) {
                item.idCard = value
            }
        })
        this.setData({
            peopleList
        })
    },
    // 清除证件号
    clearIdCard(e) {
        let {
            id
        } = e.target.dataset
        let {
            peopleList
        } = this.data
        peopleList.forEach(item => {
            if (item.id === id) {
                item.idCard = ''
            }
        })
        this.setData({
            peopleList
        })
    },

    // 删除一个隔离人
    closeItemPeople(e) {
        let {
            id
        } = e.target.dataset
        let {
            peopleList
        } = this.data
        peopleList.splice(id, 1)
        peopleList.forEach((item, index) => {
            item.id = index
        })
        this.setData({
            peopleList
        })
    },

    /* --------------------------------隔离人结束-------------------------- */
    // 确认新增隔离人员,
    confirm() {
        if (this.data.disabledBtn) return
        let {
            spaceId,
            form,
            peopleList
        } = this.data
        if (!spaceId) return showMsg("请选择隔离点")
        if (!form.type) return showMsg("请选择隔离因素")
        if (!form.mode) return showMsg("请选择隔离方式")
        if (form.region[2] === "区") return showMsg("请选择来源地区")
        if (!form.startTime) return showMsg("请选择开始时间")
        if (!form.days) return showMsg("请选择天数")
        let flag = false
        try {
            peopleList.forEach(item => {
                if (!item.name) {
                    showMsg(`请输入隔离人${item.id+1}的姓名`)
                    flag = true
                    throw new Error(`请输入隔离人${item.id+1}的姓名`);
                } else if (item.name.length < 2) {
                    showMsg(`隔离人${item.id+1}的姓名的长度不能少于2位`)
                    flag = true
                    throw new Error(`隔离人${item.id+1}的姓名的长度不能少于2位`);
                } else if (item.gender === '') {
                    showMsg(`请选择隔离人${item.id+1}的性别`)
                    flag = true
                    throw new Error(`请选择隔离人${item.id+1}的性别`);
                } else {
                    flag = false
                }
            })
        } catch (e) {
            console.log(e);
        }
        if (flag) return
        let isolationPersonList = []
        peopleList.forEach(item => {
            isolationPersonList.push({
                name: item.name,
                gender: item.gender,
                mobile: item.mobile,
                idCard: item.idCard
            })
        })
        let params = {
            orgId: app.globalData.orgId ==1?'':app.globalData.orgId,
            spaceId,
            type: form.type,
            fromCityName: `${form.region[0]}${form.region[1]}${form.region[2]}`,
            isolationStatus: 2,
            isolationType: form.mode,
            startTime: form.startTime,
            days: form.days,
            isolationPersonList
        }
        this.reqAddFun(params)

    },
    // 请求接口
    async reqAddFun(params) {
        const res = await reqisolationPersonAdd(params)
        if (res.code != 20000) return showMsg(res.message);
        showMsg("新增成功", "success")
        this.setData({
            disabledBtn: true
        })
        setTimeout(() => {
            wx.navigateBack({
                delta: 1,
            })
        }, 2000)
    },
})